<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <div class="sync_category" style="margin-bottom: 6px">
          <el-button
            type="primary"
            @click="handleCategorySync"
            :loading="syncLoad"
            plain
            style="width: 100%"
            v-hasPermi="['commodity:category:syn']"
            >同步分类</el-button
          >
        </div>
        <div class="head-container">
          <el-input
            v-model="categoryName"
            placeholder="请输入分类名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            current-node-key=""
            highlight-current
            @node-click="handleNodeClick"
            empty-text="数据加载中"
          />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="100px"
        >
          <el-form-item label="商品名称" prop="keyword">
            <el-input
              v-model="queryParams.keyword"
              placeholder="请输入商品名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="品牌" prop="brandId">
            <el-select
              v-model="queryParams.brandId"
              filterable
              placeholder="请选择品牌"
              clearable
            >
              <el-option
                v-for="item in brandList"
                :key="item.id"
                :label="item.brandName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="利润率范围">
            <el-input
              v-model="queryParams.startProfitRate"
              :min="0"
              :max="100"
              style="width: 50px"
            />
            <span style="margin: 0 5px">~</span>
            <el-input
              v-model="queryParams.endProfitRate"
              :min="0"
              :max="100"
              style="width: 50px"
            />
          </el-form-item>
          <!-- 利润率排序 -->
          <el-form-item label="利润率排序" prop="profitRateSortType">
            <el-select
              v-model="queryParams.profitRateSortType"
              placeholder="请选择"
              clearable
            >
              <el-option label="由高到底" value="1"></el-option>
              <el-option label="由低到高" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="销量排序"
            label-width="100px"
            prop="salesNumberType"
          >
            <el-select
              v-model="queryParams.salesNumberType"
              placeholder="请选择"
              clearable
            >
              <el-option label="由高到底" value="1"></el-option>
              <el-option label="由低到高" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否上架" label-width="100px" prop="isShow">
            <el-select
              v-model="queryParams.isShow"
              placeholder="请选择"
              clearable
            >
              <el-option label="已上架" value="1"></el-option>
              <el-option label="已下架" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['commodity:product:add']"
              >新增</el-button
            >
          </el-col>

          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['commodity:product:remove']"
              >删除</el-button
            >
          </el-col>

          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="multiple"
              @click="handleUpdate"
              v-hasPermi="['commodity:product:batchChangePrice']"
              >批量改价</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              size="mini"
              :disabled="multiple"
              @click="handleUp"
              v-hasPermi="['commodity:product:batchChangePrice']"
              >批量上架</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              size="mini"
              :disabled="multiple"
              @click="handleDown"
              v-hasPermi="['commodity:product:batchChangePrice']"
              >批量下架</el-button
            >
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['commodity:product:export']"
              >导出</el-button
            >
          </el-col> -->
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>
        <el-table
          v-loading="loading"
          :data="productList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="品牌" align="center" prop="goodsBrand">
            <template slot-scope="scope">
              <el-tag>{{ scope.row.goodsBrand }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="商品供应商"
            prop="goodsSupplier"
            align="center"
            width="200"
          >
            <!-- <template slot-scope="scope">
              <el-tag type="" effect="dark">{{
                scope.row.goodsSupplier
              }}</el-tag>
            </template> -->
          </el-table-column>
          <el-table-column label="商品名称" align="center" prop="productName" />

          <el-table-column
            label="商品积分数"
            align="center"
            prop="productIntegral"
          />
          <el-table-column
            label="商品支付金额"
            align="center"
            prop="productShopPrice"
          />
          <el-table-column label="供货价(元)" align="center" prop="shopPrice" />
          <el-table-column label="商品主图">
            <template slot-scope="scope">
              <el-image
                :src="scope.row.previewImg"
                fit="fill"
                :preview-src-list="[scope.row.previewImg]"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column label="是否上架" align="center" prop="isShow">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.isShow"
                :active-value="1"
                :inactive-value="0"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="是否热卖" align="center" prop="isHotSale">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.isHotSale"
                :active-value="1"
                :inactive-value="0"
                @change="handleHot(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>

          <el-table-column label="是否推荐" align="center" prop="isRecommend">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.isRecommend"
                :active-value="1"
                :inactive-value="0"
                @change="handleRecommend(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="是否返现" align="center" prop="isCashBank">
            <template slot-scope="scope">
              <el-switch
                disabled
                v-model="scope.row.isCashBank"
                :active-value="1"
                :inactive-value="0"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column
            label="返现金额"
            align="center"
            prop="cashBankPrice"
          />
          <el-table-column label="销量" align="center" prop="salesNumber" />
          <!-- 利润率 -->
          <el-table-column
            label="利润率"
            align="center"
            prop="profitRate"
            sortable
          >
            <template slot-scope="scope">
              {{
                scope.row.profitRate ? scope.row.profitRate / 100 + "%" : "--"
              }}
            </template>
          </el-table-column>
          <el-table-column label="排序" align="center" prop="sort">
            <template slot-scope="scope">
              {{ scope.row.sort }}
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleSort(scope.row)"
                v-hasPermi="['commodity:product:updateLocalSort']"
              ></el-button>
            </template>
          </el-table-column>
          <el-table-column
            label="本地设置库存数"
            align="center"
            prop="localStockNum"
          >
            <template slot-scope="scope">
              {{ scope.row.localStockNum }}
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleNum(scope.row)"
                v-hasPermi="['commodity:product:updateLocalStockNum']"
              ></el-button>
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['commodity:product:edit']"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleDetail(scope.row)"
                v-hasPermi="['commodity:product:detail']"
                >查看详情</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['commodity:product:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改商城商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="价格模式" prop="priceModel">
          <el-radio-group v-model="form.priceModel">
            <el-radio :label="1">议价</el-radio>
            <el-radio :label="2">自定义</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="议价方式"
          prop="bargainId"
          v-if="form.priceModel == 1"
        >
          <el-select v-model="form.bargainId" placeholder="请选择议价方式">
            <el-option
              v-for="item in bargainList"
              :key="item.id"
              :label="item.bargainName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="自定义价格"
          prop="setProductShopPrice"
          v-if="form.priceModel == 2"
        >
          <!-- <el-input
            v-model="form.setProductShopPrice"
            placeholder="请输入自定义价格"
            onkeyup="value=value.replace(/[^\d]/g,'')"
          ></el-input> -->
          <el-input-number
            v-model="form.setProductShopPrice"
            :precision="2"
            :step="1"
            :min="0.01"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="是否返现" prop="isCashBank">
          <el-radio-group v-model="form.isCashBank">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="返现方式"
          prop="cashBankId"
          v-if="form.isCashBank == 1"
        >
          <el-select v-model="form.cashBankId" placeholder="请选择返现方式">
            <el-option
              v-for="item in cashbackList"
              :key="item.id"
              :label="item.cashBankName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="取件方式" prop="pickUpWay">
          <el-select v-model="form.pickUpWay" placeholder="请选择取件方式">
            <el-option label="快递邮寄" :value="0"> </el-option>
            <el-option label="门店自取" :value="1"> </el-option>
            <el-option label="同时都有" :value="2"> </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="subLoading" @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 修改库存数量 -->
    <el-dialog title="修改库存数量" :visible.sync="isNum" width="400px">
      <el-form :model="numForm" ref="num" :rules="numRule" label-width="80px">
        <el-form-item label="数量" prop="localStockNum">
          <el-input
            v-model.number="numForm.localStockNum"
            placeholder="请输入商品库存数量"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormNum">确 定</el-button>
        <el-button @click="isNum = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 排序 -->
    <el-dialog title="修改排序" :visible.sync="isSort" width="400px">
      <el-form
        :model="sortForm"
        ref="sort"
        :rules="sortRule"
        label-width="80px"
      >
        <el-form-item label="排序" prop="sort">
          <el-input
            v-model.number="sortForm.sort"
            placeholder="请输入商品排序"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormSort">确 定</el-button>
        <el-button @click="isSort = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listProduct,
  delProduct,
  batchChangePrice,
  bargainList,
  category,
  updateIsShow,
  syncCategory,
  updateIsHotSale,
  updateIsRecommend,
  changeLocalStockNum,
  showBrandList,
  showBankPriceList,
  changeSort,
} from "@/api/system/product";
export default {
  name: "Product",
  data() {
    const numValidate = (rule, value, callback) => {
      if (value < 0) {
        return callback(new Error("自定义价格不得小于0元"));
      } else {
        return callback();
      }
    };
    return {
      //同步按钮加载
      syncLoad: false,
      isNum: false,
      numForm: {
        localStockNum: null,
      },
      numRule: {
        localStockNum: [
          { required: true, message: "请输入库存数量", trigger: "blur" },
        ],
      },
      isSort: false,
      sortForm: {
        sort: null,
      },
      sortRule: {
        sort: [{ required: true, message: "请输入排序", trigger: "blur" }],
      },
      subLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商城商品表格数据
      productList: [],
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      defaultProps: {
        children: "children",
        label: "title",
      },
      categoryName: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: null,
        selectCategoryId: null,
        startProfitRate: null,
        endProfitRate: null,
      },
      //议价列表
      bargainList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        bargainId: [
          { required: true, message: "请选择议价方式", trigger: "change" },
        ],
        setProductShopPrice: [
          { required: true, message: "请输入自定义价格", trigger: "blur" },
          { validator: numValidate },
        ],
      },
      brandList: [],
      //返现列表
      showBankPriceList: [],
    };
  },
  created() {
    this.getList();
    this.getDeptTree();
    this.getBrandList();
    this.getCashbackList();
    //重新请求后台，返回新的菜单列表
    // if (this.$route.query.backUserId) {
    //   this.$store
    //     .dispatch("GenerateRoutes", { userId: this.$route.query.backUserId })
    //     .then((accessRoutes) => {
    //       this.$router.addRouters(accessRoutes);
    //     });
    // }
    const mallId = this.$route.query.id;
    if (mallId) {
      this.$store.dispatch("childMallLogin", { mallId }).then(() => {
        this.$store.dispatch("GenerateRoutes").then((accessRoutes) => {
          this.$router.addRouters(accessRoutes);
        });
      });
    }
  },
  watch: {
    // 根据名称筛选部门树
    categoryName(val) {
      console.log(val);
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    // 上架
    handleUp() {},
    getCashbackList() {
      showBankPriceList().then((res) => {
        this.cashbackList = res.data;
      });
    },
    getBrandList() {
      showBrandList().then((res) => {
        this.brandList = res.data;
      });
    },
    //是否推荐
    handleRecommend(row) {
      const { productId: mallProductId, isRecommend } = row;

      let text = row.isRecommend == 1 ? "开启" : "关闭";
      this.$modal
        .confirm("确认要" + text + "推荐吗？")
        .then(function () {
          return updateIsRecommend({ mallProductId, isRecommend });
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function (err) {
          console.log(err);
          row.isRecommend = row.isRecommend == 1 ? 0 : 1;
        });
    },
    //是否返现
    handleCashBank(row) {
      const { productId: mallProductId, isCashBank } = row;

      let text = row.isCashBank == 1 ? "开启" : "关闭";
      this.$modal
        .confirm("确认要" + text + "返现吗？")
        .then(function () {
          return updateIsRecommend({ mallProductId, isCashBank });
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function (err) {
          console.log(err);
          row.isCashBank = row.isCashBank == 1 ? 0 : 1;
        });
    },
    //是否热卖
    handleHot(row) {
      const { productId: mallProductId, isHotSale } = row;

      let text = row.isHotSale == 1 ? "开启" : "关闭";
      this.$modal
        .confirm("确认要" + text + "热卖吗？")
        .then(function () {
          return updateIsHotSale({ mallProductId, isHotSale });
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function (err) {
          console.log(err);
          row.isHotSale = row.isHotSale == 1 ? 0 : 1;
        });
    },
    //修改库存
    handleNum(row) {
      this.isNum = true;
      this.numForm = {
        localStockNum: row.localStockNum,
        mallProductId: row.productId,
      };
    },
    // 修改排序
    handleSort(row) {
      this.isSort = true;
      const { productId: mallProductId, sort } = row;
      this.sortForm = {
        mallProductId,
        sort,
      };
    },
    //提交商品库存
    submitFormNum() {
      this.$refs["num"].validate((valid) => {
        if (valid) {
          changeLocalStockNum(this.numForm).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.isNum = false;
            this.getList();
          });
        }
      });
    },
    // 提交排序
    submitFormSort() {
      this.$refs["sort"].validate((valid) => {
        if (valid) {
          changeSort(this.sortForm).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.isSort = false;
            this.getList();
          });
        }
      });
    },
    //同步分类
    handleCategorySync() {
      this.syncLoad = true;
      syncCategory()
        .then((res) => {
          this.syncLoad = false;
          this.getDeptTree();
          this.$modal.msgSuccess(res.msg);
        })
        .catch((err) => {
          this.syncLoad = false;
        });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      category().then((response) => {
        const all = { id: "", title: "全部" };
        response.data.unshift(all);
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.title.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.selectCategoryId = data.id;
      this.queryParams.level = data.level;
      this.handleQuery();
    },
    //是否上架
    handleStatusChange(row) {
      const { productId: mallProductId, isShow } = row;
      let _this = this;
      let text = row.isShow == 1 ? "上架" : "下架";
      this.$modal
        .confirm("确认要" + text + "吗？")
        .then(function () {
          return updateIsShow(
            { mallProductId, isShow },
            { skipErrorToast: true }
          );
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function (err) {
          _this.$modal.alertError(err.msg);
          row.isShow = row.isShow == 1 ? 0 : 1;
        });
    },
    /** 查询商城商品列表 */
    getList() {
      this.loading = true;
      const data = {
        ...this.queryParams,
        mallId: this.$route.query.id,
      };
      listProduct(data).then((response) => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //获取议价列表
    getBargainList() {
      const mallId = this.$route.query.id;
      bargainList({ mallId }).then((res) => {
        this.bargainList = res.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        priceModel: 1,
        bargainId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 跳转详情
    handleDetail(row) {
      const id = row.productId;
      this.$router.push({
        path: "/mallGuan/goodsDetail",
        query: {
          id,
        },
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.startProfitRate = null;
      this.queryParams.endProfitRate = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.productId);
      console.log(this.ids);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      // this.reset();
      // this.open = true;
      // this.title = "添加商城商品";
      this.$router.push({
        path: "addProduct",
        query: {
          id: this.$route.query.id,
        },
      });
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.open = true;
      this.getBargainList();

      this.ids = row.productId ? [row.productId] : this.ids;
      console.log(this.ids);
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const data = {
            ...this.form,
            mallProductIds: this.ids,
          };
          this.subLoading = true;
          batchChangePrice(data, { skipErrorToast: true })
            .then((res) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.subLoading = false;
              this.getList();
            })
            .catch((err) => {
              const errMsg = err.data.join(",");
              this.$modal.alertError(errMsg);
              this.open = false;
              this.subLoading = false;
            });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const mallProductId = row.productId || this.ids;
      this.$modal
        .confirm("是否确认删除？")
        .then(function () {
          return delProduct(mallProductId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/product/export",
        {
          ...this.queryParams,
        },
        `product_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
